package com.hoolai.qps.mina.proto;

import java.net.InetSocketAddress;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.hoolai.qps.codes.mina.protobuf.ProtobufCodecFactory;
import com.hoolai.qps.proto.ReqCmdProto.SaveUserReqCmdProto;
import com.hoolai.qps.utils.StringGenerate;

public class Client {

    private static final Logger logger = Logger.getLogger(Client.class);

    private static final long CONNECT_TIMEOUT = 3000;

    public static void main(String[] args) throws InterruptedException {
        new Client(new MessageProcess());
    }

    public static class MessageProcess {
        public void sendMessage(IoSession session) {
            Scanner sc = new Scanner(System.in);
            while (true) {
                int index = sc.nextInt();
                if (index == 0) {
                    break;
                }
                SaveUserReqCmdProto.Builder builder = SaveUserReqCmdProto.newBuilder();
                builder.setName(StringGenerate.message);
                session.write(builder.build());
            }
            session.close(true);
        }
    }

    public Client(MessageProcess message) throws InterruptedException {
        NioSocketConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(ProtobufCodecFactory.newInstance(SaveUserReqCmdProto.newBuilder().build())));
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new IoHandlerAdapter() {
            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                logger.info("client message received:\n" + message);
            }
        });

        try {
            ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 8888));
            future.awaitUninterruptibly();
            IoSession session = future.getSession();
            message.sendMessage(session);
        } catch (RuntimeIoException e) {
            System.err.println("Failed to connect.");
            e.printStackTrace();
            Thread.sleep(5000);
        }

    }

}
